package com.schoolhelper.model.dao.okhttp;

import com.schoolhelper.model.Model;
import com.schoolhelper.model.dao.jsonparse.JsonParser;
import com.schoolhelper.model.dao.jsonparse.LwlJsonParser;
import com.schoolhelper.model.entity.Order;

import java.io.File;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import lombok.SneakyThrows;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LwlRequestUrl extends RefactorRequestUrl{

    @SneakyThrows
    public static String getPostSmms(String baseUrl, String api, Map<String, String> headers, File file) {

        OkHttpClient client = OkHttpUtil.getInstance();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

//                .addFormDataPart("smfile", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);//上传的文件以及类型, image或者video
        builder.addFormDataPart("smfile", file.getName(), requestBody);// 参数：请求key,文件名称,RequestBody
        Request request = new Request.Builder()
                .url(baseUrl + "/" + api)
                .headers(Headers.of(headers))
                .post(builder.build())
                .build();

        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Response response = client.newCall(request).execute();
                return response.body().string();
            }
        };
        Future<String> response = Model.getInstance().getGlobalThreadPool().submit(callable);
        return response.get();
    }

    @SneakyThrows
    public static String postSmmsThenGetUrl(String baseUrl, String api, Map<String, String> headers, File file,
                                            LwlJsonParser jsonParser) {

        String responseData = getPostSmms(baseUrl, api, headers, file);
        return jsonParser.getSmmsUrl(responseData);
    }
}
